import qs from 'qs';
import React, { useState } from 'react';
// import { makeStyles } from '@material-ui/core/styles';
import { useHistory, useLocation } from 'react-router';
import { ErrorDialog } from './ErrorDialog';

/* const useStyles = makeStyles({
  root: {
    width: '100%',
    // height: 'auto',
  },
  media: {
    width: '100%',
    height: '100vh',
  },
}); */

interface ImageCardProp {
  src: string;
  previousImageName: string;
  nextImageName: string;
}
export default function ImageCard({ src, previousImageName, nextImageName }: ImageCardProp) {
  // const classes = useStyles();
  const [touchStartX, setTouchStartX] = useState(0);
  const [touchEndX, setTouchEndX] = useState(0);
  const [isError, setIsError] = useState(false);
  const [message, setMessage] = useState('');
  const history = useHistory();
  const { search } = useLocation<Location>();
  const { directory } = qs.parse(search.substring(1)) as any;

  const handleTouchEnd = () => {
    if (touchEndX === 0) return;
    if (touchEndX - touchStartX > 50) {
      setTouchEndX(0);
      if (previousImageName === undefined) {
        setIsError(true);
        setMessage('已经是第一张图片了');
        return;
      }
      history.replace('image?' + qs.stringify({ directory, name: previousImageName }));
    } else if (touchStartX - touchEndX > 50) {
      setTouchEndX(0);
      if (nextImageName === undefined) {
        setIsError(true);
        setMessage('已经是最后一张图片了');
        return;
      }
      history.replace('image?' + qs.stringify({ directory, name: nextImageName }));
    }
  };
  return (
    <>
      <div
        onTouchStart={e => setTouchStartX(e.touches[0].clientX)}
        onTouchMove={e => setTouchEndX(e.touches[0].clientX)}
        onTouchEnd={handleTouchEnd}
      >
        <img
          src={src}
          alt={'图片'}
          style={{
            width: '100%',
            height: '100%',
            objectFit: 'cover',
          }}
        />
        {/* <Card className={classes.root}>
          <CardActionArea>
            <CardMedia className={classes.media} image={src} title="Contemplative Reptile" />
          </CardActionArea>
        </Card> */}
      </div>
      <ErrorDialog isError={isError} setIsError={setIsError} message={message} />
    </>
  );
}
